package com.xiaoming.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;

public class StaticResourceUtil {
    public static String path = "";

    /***
     *  获取文件绝对路径
     * @param url
     * @return
     */
    public static String getAbsolutePath(String url) throws URISyntaxException {
        return path + url;
    }

    /***
     * 读取静态资源输出
     * @param inputStream
     * @param outputStream
     * @throws IOException
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        int resourceSize = count;
        // 输出：请求头、内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        // 读取文件
        long written = 0; //已读取长度
        int byteSize = 1024; // 读取1024
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            // 一个字节数组就能写完，按真实长度处理
            if (written + byteSize > resourceSize) {
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }

    }

}